const Teacher = require('../models/teacher');
const User = require('../models/user');
const passwordUtils = require('../utils/passwordUtils');

// 教师控制器
const teacherController = {
  // 获取所有教师
  async getAllTeachers(ctx) {
    try {
      const teachers = await Teacher.find().populate('userId');
      ctx.body = {
        success: true,
        data: teachers,
        count: teachers.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取教师列表失败',
        error: error.message
      };
    }
  },

  // 根据ID获取教师
  async getTeacherById(ctx) {
    try {
      const teacher = await Teacher.findById(ctx.params.id).populate('userId');
      if (!teacher) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '教师不存在'
        };
        return;
      }
      ctx.body = {
        success: true,
        data: teacher
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取教师信息失败',
        error: error.message
      };
    }
  },

  // 创建教师
  async createTeacher(ctx) {
    try {
      const { teacherId, name, gender, age, position, academy, phone, email, subjects } = ctx.request.body;

      // 检查工号是否已存在
      const existingTeacher = await Teacher.findOne({ teacherId });
      if (existingTeacher) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '工号已存在'
        };
        return;
      }

      // 创建用户账号
      const defaultPassword = 'Teacher123!';
      const hashedPassword = await passwordUtils.hashPassword(defaultPassword);
      const user = new User({
        username: teacherId.toLowerCase(),
        name: name,
        email: email || `${teacherId}@example.com`,
        password: hashedPassword,
        phone: phone,
        role: 'teacher',
        status: 'active'
      });
      await user.save();

      // 创建教师记录
      const teacher = new Teacher({
        teacherId,
        name,
        gender,
        age,
        position,
        academy,
        phone,
        email: email || `${teacherId}@example.com`,
        subjects,
        userId: user._id
      });
      await teacher.save();

      ctx.status = 201;
      ctx.body = {
        success: true,
        message: '教师创建成功',
        data: teacher,
        defaultPassword: defaultPassword
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '创建教师失败',
        error: error.message
      };
    }
  },

  // 更新教师信息
  async updateTeacher(ctx) {
    try {
      const teacher = await Teacher.findById(ctx.params.id);
      if (!teacher) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '教师不存在'
        };
        return;
      }

      // 检查当前用户是否有权限更新
      const currentUser = ctx.state.user;
      if (currentUser.role !== 'admin' && currentUser._id.toString() !== teacher.userId.toString()) {
        ctx.status = 403;
        ctx.body = {
          success: false,
          message: '无权限更新其他教师信息'
        };
        return;
      }

      const updateData = ctx.request.body;
      // 更新教师信息
      Object.assign(teacher, updateData);
      await teacher.save();

      // 更新关联的用户信息
      await User.findByIdAndUpdate(teacher.userId, {
        name: updateData.name || teacher.name,
        phone: updateData.phone || teacher.phone,
        email: updateData.email || teacher.email
      });

      ctx.body = {
        success: true,
        message: '教师信息更新成功',
        data: teacher
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '更新教师信息失败',
        error: error.message
      };
    }
  },

  // 删除教师
  async deleteTeacher(ctx) {
    try {
      const teacher = await Teacher.findById(ctx.params.id);
      if (!teacher) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '教师不存在'
        };
        return;
      }

      // 删除关联的用户账号
      await User.findByIdAndDelete(teacher.userId);
      
      // 删除教师记录
      await Teacher.findByIdAndDelete(ctx.params.id);

      ctx.body = {
        success: true,
        message: '教师删除成功'
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '删除教师失败',
        error: error.message
      };
    }
  },

  // 分页获取教师列表
  async getTeachersPaginated(ctx) {
    try {
      const page = parseInt(ctx.query.page) || 1;
      const limit = parseInt(ctx.query.limit) || 10;
      const skip = (page - 1) * limit;

      // 构建查询条件
      const query = {};
      if (ctx.query.academy) {
        query.academy = ctx.query.academy;
      }
      if (ctx.query.position) {
        query.position = ctx.query.position;
      }

      const teachers = await Teacher.find(query)
        .skip(skip)
        .limit(limit)
        .populate('userId')
        .sort({ createdAt: -1 });

      const total = await Teacher.countDocuments(query);

      ctx.body = {
        success: true,
        data: teachers,
        pagination: {
          total,
          page,
          limit,
          pages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取分页教师列表失败',
        error: error.message
      };
    }
  },

  // 根据学院获取教师列表
  async getTeachersByAcademy(ctx) {
    try {
      const teachers = await Teacher.find({ academy: ctx.params.academy })
        .populate('userId');
      
      ctx.body = {
        success: true,
        data: teachers,
        count: teachers.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取学院教师列表失败',
        error: error.message
      };
    }
  },

  // 获取教师教授的科目
  async getTeacherSubjects(ctx) {
    try {
      const teacher = await Teacher.findById(ctx.params.id);
      if (!teacher) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '教师不存在'
        };
        return;
      }
      
      ctx.body = {
        success: true,
        data: {
          teacherId: teacher.teacherId,
          name: teacher.name,
          subjects: teacher.subjects
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取教师科目失败',
        error: error.message
      };
    }
  }
};

module.exports = teacherController;